package view;

import model.Table;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * Display in a Scatter Plot Graph
 * @author David
 */
public class ScatterPlotMode extends GeneralDisplayMode {
    //sort according to this column

    /**
     * construct Scatter Plot
     * @param dataTable sub-table of data
     * @param categoryNames categories to be displayed
     */
    public ScatterPlotMode (Table dataTable, String[] categoryNames) {
        super(dataTable, categoryNames);
        setSortIndex(2);
    }

    @Override
    /**
     * make the graph according to the given dataTable
     * a panel on which the graph is drawn
     */
    public ChartPanel constructChartPanel () {
        JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot",
                /* x axis label*/ getCategoryNames()[0], 
                /* y axis label*/ getCategoryNames()[1], 
                /* data*/ createDataset(),
                /* include legend*/ PlotOrientation.HORIZONTAL, false,
                /* tooltips*/ true, 
                /* urls*/false);
        ChartPanel panel = new ChartPanel(chart, true);
        return panel;
    }

    private XYDataset createDataset () {
        XYSeriesCollection result = new XYSeriesCollection();
        XYSeries series = new XYSeries("set1");
        for (int i = 0; i < getDataSize(); i++) {
            double x = 0;
            double y = 0;
            try {
                x = Double.parseDouble(getTable().getData(i, 1).getValue());
                y = Double.parseDouble(getTable().getData(i, 2).getValue());
            }
            catch (NumberFormatException e) {
                /*
                 * this should not happen because the type of data in the
                 * available categories have already been checked to be doubles
                 */
                e.printStackTrace();
            }
            series.add(x, y);
        }
        result.addSeries(series);
        return result;
    }

    /**
     * sort in ascending order
     */
    public void sortAscending () {
        getTable().sortAscending(getSortIndex());
    }

    /**
     * sort in descending order
     */
    public void sortDescending () {
        getTable().sortDescending(getSortIndex());
    }
}
